//
//  ViewController.m
//  MVP4
//
//  Created by 李煜 on 2024/6/21.
//

#import "ViewController.h"
#import "UserPresenter.h"
#import "UserView.h"
#import "UserViewData.h"
#import "UserService.h"

#warning //https://www.jianshu.com/p/a4ed73c05dbc
@interface ViewController()<UITableViewDataSource, UserView>

@property (weak, nonatomic) IBOutlet UIView *emptyView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;

@property (nonatomic, strong) UserPresenter *userPresenter;
@property (nonatomic, strong) NSArray *usersToDisplay;

@end

@implementation ViewController

#pragma mark - life cycles
- (void)viewDidLoad {
    [super viewDidLoad];
    
    _tableView.dataSource = self;
    _activityIndicator.hidesWhenStopped = YES;
    
    // 绑定视图
    [self.userPresenter attachView:self];
    // 获取用户数据
    [self.userPresenter getUsers];
}

#pragma mark - UserView
- (void)startLoading {
    [_activityIndicator startAnimating];
}

- (void)finishLoading {
    [_activityIndicator stopAnimating];
}

- (void)setUsers:(NSArray<UserViewData *> *)users {
    _usersToDisplay = users;
    _tableView.hidden = NO;
    _emptyView.hidden = YES;
    [_tableView reloadData];
}

- (void)setEmptyUsers {
    _tableView.hidden = YES;
    _tableView.hidden = NO;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.usersToDisplay.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"UserCell"];
    UserViewData *user = [self.usersToDisplay objectAtIndex:indexPath.row];
    cell.textLabel.text = user.name;
    cell.detailTextLabel.text = user.age;
    return cell;
}

#pragma mark - getters and setters
- (UserPresenter *)userPresenter {
    if (_userPresenter == nil) {
        UserService *userService = [[UserService alloc] init];
        _userPresenter = [[UserPresenter alloc] initWithUserService:userService];
    }
    return _userPresenter;
}

- (NSArray *)usersToDisplay {
    if (_usersToDisplay == nil) {
        _usersToDisplay = [NSArray array];
    }
    return _usersToDisplay;
}

@end
